﻿/*
#-------------------------------------------------------------------------------
# Name:        Digit Segmentation
#
# Author:      Groep 6
# Modified by: Duncan Jenkins
#
#-------------------------------------------------------------------------------
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;

namespace LibraryCS {
    public partial class SegmentationAlgorithm : VisionAlgorithm {
        public SegmentationAlgorithm(String name) : base(name) { }

        public override Bitmap DoAlgorithm(Bitmap sourceImage) {
            throw new NotImplementedException();
        }

        public List<VImage> SegmentDigits(VImage licensePlate) {
            List<VImage> CharacterList = new List<VImage>();

            List<Blob> blobs = BlobDetection.DetectBlobs(licensePlate);

            blobs.Sort((x, y) => x.minx.CompareTo(y.minx));
            int pixels = licensePlate.Width * licensePlate.Height;

            foreach (Blob b in blobs) {
                if (b.amountOfPixels < pixels / 1150)
                    continue;
                if (b.maxx - b.minx < 5)
                    continue;

                if (!(Math.Abs(b.maxx - b.minx) > Math.Abs(b.maxy - b.miny))) {
                    VImage digit = new VImage(licensePlate);
                    digit = digit.Crop(b.minx, b.miny, b.maxx, b.maxy);
                    digit.blob = b;
                    CharacterList.Add(digit);
                }
            }

            // Backup / Failsafe?
            if (CharacterList.Count == 0) {
                foreach (Blob b in blobs) {
                    if (b.amountOfPixels < pixels / 2500)
                        continue;
                    if (b.maxx - b.minx < 5)
                        continue;
                    if (!(Math.Abs(b.maxx - b.minx) > Math.Abs(b.maxy - b.miny))) {
                        VImage digit = new VImage(licensePlate).Crop(b.minx, b.miny, b.maxx, b.maxy);
                        digit.blob = b;
                        CharacterList.Add(digit);
                    }
                }
            }

            if (CharacterList.Count < 4) {
                CharacterList.Clear();
            }

            if (CharacterList.Count > 6) {
                CharacterList = new List<VImage>(CharacterList.GetRange(0, 6));
            }

            Debug.WriteLine("Aantal blobs op kenteken: " + CharacterList.Count);

            return CharacterList;
        }
    }
}
